<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => {
          unfoldFlag = v;
        }
        ">
      </SearchForm>
    </template> 
    <template v-slot:btn>
      <BtnSlot :btnList="selectIndex == 0 ? ['add'] : btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:tab>
      <EnumSlot v-loading="loading" @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="buttonselectlist"
        :labelKey="'value'">
      </EnumSlot>
    </template>
    <template v-slot:table>
      <TableData @selection-change="selectionChange" :tableThead="tableThead" :dataList="dataList" :loading="loading"
      :config="selectIndex == 0 ? {
        ...table_config,
        isOperation: false,
      } : { ...table_config }" >
        <template v-slot:seeDetail="{ row }">
          <span class="successText" @click="lookView(row)">查看详情</span>
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="handleCurrentChange" :page="page" :size="size" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <SeeaddEdit :title="'动保药物'" @closeDialog="() => {
        dialogVisibleLookView = false;
      }" :dialogVisible="dialogVisibleLookView" addEditFlag="edit" :tableThead="tableThead"
        :dialogtableThead="dialogtableThead" :data="seeformData"></SeeaddEdit>

      <AddEdit :title="'动保药物'" @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible"
        :data="seeformData" :StordocList="StordocList" :OrgDeptList="OrgDeptList" :PsndocList="PsndocList"
        :OrgOrgsList="OrgOrgsList" :MaterialList="MaterialList" :Defdoc2List="Defdoc2List"></AddEdit>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from "@/components-production-management/Pagination";
import SearchForm from "@/components-production-management/SearchForm";
import BtnSlot from "@/components-production-management/BtnSlot";
import TableData from "@/components-production-management/TableData";
import EnumSlot from '@/components-production-management/EnumSlot';
//NC批次
import AddEdit from "./components/addEdit.vue";
import SeeaddEdit from "./components/SeeaddEdit.vue";
import ncQueryApi from "@/api/nc-query/index";
import ncmaterialApi from "@/api/production-management-nc/material-input-nc";
import ncBasicinfoApi from "@/api/nc-basic-info/index";

export default {
  components: { MainSlot, Pagination, SearchForm, TableData, AddEdit, BtnSlot, SeeaddEdit,EnumSlot },
  data() {
    return {
      btnList: ["add", "delete"],
      addEditFlag: "add",
      dialogVisible: false,
      seeformData: {},
      formData: {},
      StordocList: [], //仓库
      OrgDeptList: [], //部门
      PsndocList: [], //人员
      OrgOrgsList: [], //组织
      MaterialList: [], //物料
      Defdoc2List: [], //活鱼品规
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: "操作",
          width: "300",
          cols: [
            {
              label: "编辑",
              type: "primary",
              flag: "edit",
              handleRow: this.handleRow,
            },
            {
              label: "删除",
              type: "danger",
              flag: "del",
              handleRow: this.handleRow,
            },
            {
              label: "确认提交",
              type: "primary",
              flag: "submit",
              handleRow: this.handleRow,
            }
          ],
        },
      },
      //======================
      selectList: [],
      unfoldFlag: false,
      loading: false,
      dialogVisibleLookView: false,
      tableData: [],
      page: 1,
      size:30,
      total: 10,
      selectIndex:0,
      buttonselectlist: [
        { name: "submit", value: "已提交" },
        { name: "save", value: "暂存" }
      ],
      searchFormData: {},
      dataList: [],
      dialogtableThead: [
        {
          label: "物料编码",
          prop: "cmaterialvname",
        },

        {
          label: "主单位",
          prop: "cunitname",
        },
        {
          label: "辅单位",
          prop: "castunitname",
        }, {
          label: "换算率",
          prop: "vchangerate",
        }, 
        // {
        //   label: "养殖批次号",
        //   prop: "vproductbatch",
        // },
        {
          label: "应发辅数量",
          prop: "nshouldassistnum",
        },
        {
          label: "实发辅数量",
          prop: "nassistnum",
        },
        {
          label: "应发主数量",
          prop: "nshouldnum",
        }, {
          label: "实发主数量",
          prop: "nnum",
        },
        // {
        //   label: "条数",
        //   prop: "vbdef1",
        // },
        // {
        //   label: "均重",
        //   prop: "vbdef2",
        // },
        // {
        //   label: "批次号",
        //   prop: "vbatchcode",
        // },
        // {
        //   label: "活鱼品规名称",
        //   slotName: "vfree1",
        // },
      ],
      tableThead: [
        {
          isShow: true,
          label: "库存组织",
          prop: "pk_orgname",
          minWidth: "120px",
        },
        {
          isShow: true,
          label: "仓库名称",
          prop: "cwarehousename",
          minWidth: "120px",
        },
        {
          isShow: true,
          label: "领料部门",
          prop: "cdptname",
          minWidth: "120px",
        },

        {
          isShow: true,
          label: "业务员",
          prop: "cwhsmanagername",
          minWidth: "120px",
        },
        {
          isShow: true,
          label: "单据号",
          prop: "vbillcode",
          minWidth: "120px",
        },
        {
          isShow: true,
          label: "单据日期",
          prop: "dbilldate",
          minWidth: "120px",
        },
        {
          isShow: true,
          label: "查看详情",
          slotName: "seeDetail",
          minWidth: "120px",
        },
      ],

      formItemList: [
        {
          label: "单据号",
          type: "input",
          param: "vbillcode",
          multiple: false,
          isShow: true,
        },
        // {
        //   label: "养殖批次号",
        //   type: "input",
        //   param: "vproductbatch",
        //   multiple: false,
        //   isShow: true,
        // },
        // {
        //   label: "仓库",
        //   type: "select",
        //   selectOptions: [],
        //   param: "cwarehouseid",
        //   defaultSelect: "", // 下拉框默认选中项
        //   multiple: false,
        //   isShow: true,
        // },
        {
          label: "鱼塘名称",
          type: "select",
          selectOptions: [],
          param: "cdptid",
          defaultSelect: "", // 下拉框默认选中项
          multiple: false,
          isShow: true,
        },

        {
          label: "日期查询",
          type: "datetimerange",
          defaultSelect: [],
          param: "dateTime",
          multiple: false,
          isShow: true,
        },
      ],
    };
  },
  mounted() {
    this.queryPageByCondition();
    this.queryStordoc(); //Stordoc仓库
    this.queryOrgDept(); //部门
    this.queryPsndoc(); //业务员
    this.queryOrgOrgs(); //组织
    this.queryMaterial(); //物料
    this.queryDefdoc2(); //活鱼品规
  },
  methods: {
    getEnumEvent(enumInfo) {
      let { data, index } = enumInfo;
      this.selectIndex = index
      console.log(data, index)
      this.queryPageByCondition();
    },
    // 查询仓库鱼塘
    queryStordoc() {
      ncBasicinfoApi
        .queryStordoc({ pk_org: JSON.parse(localStorage.ncOrg) })
        .then((res) => {
          this.StordocList = res.data || [];
          this.setFormOptions();
        });
    },
    // 查询部门
    queryOrgDept() {
      ncBasicinfoApi
        .queryOrgDept({ pk_org: JSON.parse(localStorage.ncOrg) })
        .then((res) => {
          this.OrgDeptList = res.data || [];
          this.setFormOptions();
        });
    },
    // 查询人员
    queryPsndoc() {
      ncBasicinfoApi
        .queryPsndoc({ pk_org: JSON.parse(localStorage.ncOrg) })
        .then((res) => {
          this.PsndocList = res.data || [];
          this.setFormOptions();
        });
    },
    // 查询组织
    queryOrgOrgs() {
      ncBasicinfoApi
        .queryOrgOrgs({ pk_org: JSON.parse(localStorage.ncOrg) })
        .then((res) => {
          this.OrgOrgsList = res.data || [];
        });
    },
    // 查询物料
    queryMaterial() {
      ncBasicinfoApi
        .queryMaterial({ pk_parent: "1001A110000000003G5D" })
        .then((res) => {
          this.MaterialList = res.data || [];
        });
    },
    // 活鱼品规
    queryDefdoc2() {
      ncBasicinfoApi.queryDefdoc2().then((res) => {
        this.Defdoc2List = res.data || [];
      });
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = [];
      list.forEach((item, index) => {
        // if (item.param.indexOf("cwarehouseid") !== -1) {
        //   let selectOptions = this.StordocList.map((data) => {
        //     return {
        //       text: data.name,
        //       value: data.pk_stordoc,
        //     };
        //   });
        //   item.selectOptions = selectOptions;
        // }
        if (item.param.indexOf("cmaterialvid") !== -1) {
          let selectOptions = this.MaterialList.map((data) => {
            return {
              text: data.name,
              value: data.pk_material,
            };
          });
          item.selectOptions = selectOptions;
        }
        if (item.param.indexOf("cdptid") !== -1) {
          let selectOptions = this.OrgDeptList.map((data) => {
            return {
              text: data.name,
              value: data.pk_dept,
            };
          });
          item.selectOptions = selectOptions;
        }
      });
      this.$nextTick(() => {
        this.$set(this, "formItemList", list);
      });
    },
    queryNcSearchKey() {
      let form = {}
      let { cdptid, cwarehouseid, vproductbatch, endDate, startDate } = this.searchFormData;
      let rut_cdpt = this.OrgDeptList.find(e => { return e.pk_dept == cdptid }) || {}
      let rut_cwarehouse = this.StordocList.find(e => { return e.pk_stordoc == cwarehouseid }) || {}
      // console.log(cdptid, cwarehouseid, vproductbatch, endDate, startDate)
      console.log(cwarehouseid, rut_cwarehouse)
      console.log(cdptid, rut_cdpt)
      form = {
        endDate,
        startDate,
        vproductbatch,
        cdptid: rut_cdpt.code,
        cwarehouseid: rut_cwarehouse.code
      }
      return this.selectIndex == 0 ? this.searchFormData : form
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.queryNcSearchKey(),
        },
      };
      this.loading = true;
      let api = null;
      if (this.selectIndex == 0) {
        api = ncmaterialApi.queryPageByCondition_nc
      } else {
        api = ncmaterialApi.queryPageByCondition
      }
      api(params).then((res) => {
          this.loading = false;
          if (res.success == 1) {
            this.dataList = res.data.content || [];
            this.total = res.data.totalElements;
            if (res.data.totalPages && this.page > res.data.totalPages) {
              this.page = res.data.totalPages;
              this.queryPageByCondition();
            }
          } else {
            this.$message.warning(res.message || "分页查询失败");
          }
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    },
    search(data) {
      this.page = 1;
      if (data.dateTime && data.dateTime.length) {
        data.startDate = data.dateTime[0];
        data.endDate = data.dateTime[1];
      }
      delete data.dateTime;
      this.searchFormData = { ...data };

      for (let key in this.searchFormData) {
        if (!this.searchFormData[key]) {
          this.searchFormData[key] = null;
        }
      }
      console.log(this.searchFormData, data, "this.searchFormData");
      this.queryPageByCondition();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },

    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.dialogVisible = true;
      } else if (flag == "delete") {
        if (this.selectList.length > 0) {
          this.delList(this.selectList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      }
      this.addEditFlag = flag;
    },

    // table操作方法
    async handleRow(rowData, item) {
      if (item.flag == "del") {
        this.delList([rowData]);
      } else if (item.flag == "edit") {
        let obj = JSON.parse(JSON.stringify(rowData));
        let api = null;
        let orderId = ''
        if (this.selectIndex == 0) {
        api = ncmaterialApi.queryDtl_nc
        orderId = obj.cgeneralhid
      } else {
        api = ncmaterialApi.queryDtl
        orderId = obj.id
      }
        let res = await api({ orderId });
        if (res.success) {
          this.tableData = res.data || [];
          if (res.success) {
            this.tableData = res.data || [];
            this.seeformData = obj;
            this.seeformData.detailList = res.data || [];
            this.dialogVisible = true;
          }
          console.log(this.seeformData)
        }
      } else if (item.flag == "submit") {
        this.submitNc(rowData)
      }
      this.addEditFlag = item.flag;
    },
    async submitNc(rowData) {
      let list = { ic_generalout_b: [], ic_generalout_h: {} };
      let { data: detailList } = await ncmaterialApi.queryDtl({ orderId: rowData.id });
      list = { ic_generalout_b: detailList || [], ic_generalout_h: { ...rowData } };
      console.log(list)
      this.$confirm("此操会将该暂存数据提交到ncc,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.loading = true
        ncmaterialApi.add_nc([list]).then(async res => {
          this.loading = false
          if (res.success) {
            let { success } = await ncmaterialApi.delById(rowData.id);
            success && this.queryPageByCondition();
            success && this.$message.success('操作成功');
          } else {
            !res.success && this.errAlert(res.message)
          }
        }).catch((err) => {
          console.log(err)
          this.loading = false
          this.$message({
            type: "info",
            message: "操作失败",
          });
        })
      }).catch((err) => {
        console.log(err)
        this.loading = false
        this.$message({
          type: "info",
          message: "已取消",
        });
      })
    },
    errAlert(text) {
      this.$alert(text, '提示', {
        confirmButtonText: '确定',
        callback: action => { }
      });
    },
    //批量删除
    delList(deleteList = [], key = "id") {
      let list = [];
      deleteList.forEach((item) => {
        list.push(item[key]);
      });

      console.log(list);
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await ncmaterialApi.delListById(list);
          if (res.success) {
            this.$message.success(res.message || "删除成功");
            this.queryPageByCondition();
          } else {
            this.$message.warning(res.message || "删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 多选方法
    selectionChange(val) {
      console.log(val);
      this.selectList = val || [];
    },

    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
    //查看详情
    async lookView(row) {
      let obj = JSON.parse(JSON.stringify(row));
      let api = null;
      let orderId = ''
      if (this.selectIndex == 0) {
        api = ncmaterialApi.queryDtl_nc
        orderId = obj.cgeneralhid
      } else {
        api = ncmaterialApi.queryDtl
        orderId = obj.id
      }
      let res = await api({ orderId });
      if (res.success) {
        this.tableData = res.data || [];
        // this.dialogVisibleLookView = true;
        this.seeformData = obj;
        this.seeformData.detailList = res.data || [];
        this.seeformData.detailList = this.seeformData.detailList.map(item => {
          return {
            ...item,
            cmaterialvname: this.selectIndex == 0 ? `${item.cmaterialvcode}/${item.cmaterialvname}` : item.cmaterialvname
          }
        })
        this.dialogVisibleLookView = true;
      }
    },
  },
};
</script>
<style lang="scss" scoped></style>